<template>
    <div>
        <van-nav-bar
            style="background-color: #EDEDED;"
            :title="$store.state.list.uname"
            right-text="..."
            left-arrow
            @click-left="onClickLeft"
            @click-right="onClickRight"
            />
        <ul :style="sjiaodian" id="messageList">
            <li v-for="xiao in $store.state.xiaoxi" :class="xiao.mfromuserid === $store.state.udate.uid?'a':'b'">
                <img :src="xiao.mfromuserid === $store.state.udate.uid ? $store.state.udate.uimg : $store.state.list.uimg" 
                    :class="xiao.mfromuserid === $store.state.udate.uid?'aimg':'bimg'">

                    <div :class="xiao.mfromuserid === $store.state.udate.uid?'adiv':'bdiv'">
                       <p  :class="xiao.mfromuserid === $store.state.udate.uid?'ap':'bp'" >
                        {{xiao.mpostmessages}}
                    </p> 
                    </div>
                    
                <!-- <p style="margin-top:30%;text-align: center;background-color: #ffffff;opacity:0.7;">{{dateFormat('YYYY-mm-dd HH:MM',xiao.mtime)}}</p> -->
            </li> 
        </ul>
        <div style="width: 100%; 
            background-color: #EDEDED;
            height: 60px;  position: fixed;
            left: 0px;
            right: 0px;
            bottom: 0px;
            text-align: center;">
            <input type="text" 
                style="height: 35px;
                width: 250px;
                margin-left: 3%;
                margin-top: 2%;
                border-radius: 5px;
                border: none;
                 " v-model="input" @keyup.enter="queding">
            <button class="queding1" @click="queding">发送</button>
        </div>
    </div>
</template>
  
<script>

import axios from 'axios'
export default {
    name: 'Chatpage',
    data() {
        return {
            sjiaodian:'height: 673px;overflow:auto;',
            docmHeight: document.documentElement.clientHeight, // 默认屏幕可视高度
            showHeight: 0, //body元素高度
            isShow: true, //显示或隐藏
            input:'',
            silderName:''//路由动画
        }
    },
    
    mounted(){

        //当页面加载滚动条直接拉到最底部
        setTimeout(() => {
            const message = document.getElementById('messageList')
            message.scrollTop = message.scrollHeight + 100
        }, 300);

        //从前面获取参数
        // this.list=this.$route.query.list
        // window.onresize监听页面高度的变化
        window.onresize = () => {
            return(()=>{
                this.showHeight = document.body.clientHeight
            })()
        }
        if ('WebSocket' in window) {
        this.websocket = new WebSocket('ws://8.130.95.37:8085/websocket/'+this.$store.state.udate.uid);
        this.websocket.onopen = () => {
            console.log("开启ws")
        }
        this.websocket.onclose = () => {
            console.log('关闭ws')
        }
        this.websocket.onerror = () => {
            console.log('出错')
        }
        this.websocket.onmessage = (e) => {
            console.log(JSON.parse(e.data))
            let message = JSON.parse(e.data)
            message.mid = this.$store.state.xiaoxi.length
            if (this.$store.state.list.uid == JSON.parse(e.data).mfromuserid) {
                this.$store.state.xiaoxi.push(message)
            }
            
            setTimeout(() => {
                const message = document.getElementById('messageList')
                message.scrollTop = message.scrollHeight + 100
            }, 300);
        }
        } else {
            alert('当前浏览器不支持WebSocket!!!')
        }
        window.onbeforeunload = () => {
            this.websocket.close()
        }
        const options = {
          method: 'POST',
          headers: {
            "Content-Type": 'application/json'
          }
        }
        fetch(`http://8.130.95.37:8085/getmessages/${this.$store.state.udate.uid}/${this.$store.state.list.uid}`, options).then(res => res.json()).then(res => {
            this.$store.state.xiaoxi=res
        }).catch(err => {
          console.log(err)
        })
    },
    methods:{
        onClickRight() {
            this.$router.push('/deleteafriend')
        },
        onClickLeft(){
            this.$router.push('/home/list')
        },
        queding(){
            const object = JSON.stringify({mfromuserid: this.$store.state.udate.uid, mpostmessages: this.input, mtouserid: this.$store.state.list.uid})
            if (this.websocket.readyState===1) {
                this.websocket.send(object)
            }
            axios.post(`http://8.130.95.37:8085/message`, JSON.parse(object)).then(res => {
                // if (this.$store.state.list.uid == JSON.parse(res.config.data).mtouserid) {
                this.$store.state.xiaoxi.push({mid: res.data, mfromuserid: this.$store.state.udate.uid, mpostmessages: this.input, mtouserid: this.$store.state.list.uid, mtime: new Date()})
                
                
                this.input=''
                setTimeout(() => {
                    const message = document.getElementById('messageList')
                    message.scrollTop = message.scrollHeight + 100
                }, 300);
            }).catch(err => console.log(err))
        },
        dateFormat(fmt, date) {
        let ret="";
        date=new Date(date);
        const opt = {
            'Y+': date.getFullYear().toString(), // 年
            'm+': (date.getMonth() + 1).toString(), // 月
            'd+': date.getDate().toString(), // 日
            'H+': date.getHours().toString(), // 时
            'M+': date.getMinutes().toString(), // 分
            'S+': date.getSeconds().toString() // 秒
            // 有其他格式化字符需求可以继续添加，必须转化成字符串
        }
        for (let k in opt) {
            ret = new RegExp('(' + k + ')').exec(fmt)
            if (ret) {
            fmt = fmt.replace(
                ret[1],
                ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, '0')
            )
            }
        }
        return fmt
        }
    },
    beforeDestroy(){
        this.websocket.close()
    },
    watch: {
        showHeight() {
            if(this.docmHeight > this.showHeight){
                this.isShow = false
            }else{
                this.isShow = true
            }
        },
       

    }

    


    
}
</script>

<style scoped>
.b{
    width: 100%;float: left;overflow: hidden;
}
.a{
    width: 100%;float: right;overflow: hidden;
}
.bimg{
    width: 50px;
    height: 50px;
    border-radius: 5px;
    margin-left: 5%;
    margin-top: 10%;float: left;
}
.aimg{
    width: 50px;
    height: 50px;
    border-radius: 5px;
    margin-right: 5%;
    margin-top: 10%;float: right;
}
.bp{
    float: left;
    margin-top: 7%;
    background-color: #ffffff;
    margin-left: 3%;
    /* width: 168px; */
    word-wrap:break-word;  
    word-break:break-all;
    padding-top: 7.5%;
    padding-bottom: 7%;
    border-radius: 4px;
    padding-left: 5%;
    padding-right: 5%;        
}

.ap{
    float: right;
    margin-top: 7%;
    background-color: #95EC69;
    margin-right: 3%;
    /* width: 168px; */
    word-wrap:break-word;  
    word-break:break-all;
    padding-top: 7.5%;
    padding-bottom: 7%;
    border-radius: 4px;
    padding-left: 5%;
    padding-right: 5%;               
}
.adiv{
    width: 168px;
    float: right;
    margin-top: 7.5%;
}
.bdiv{
    width: 168px;
    float: left;
    margin-top: 7.5%;
}
/* 发送按钮样式及悬浮样式 */
.queding1{
    width: 70px;
    height: 35px;
    border-radius: 5px;
    margin-left: 3%;
    background-color: #05C160;
    border: none;color: #ffffff;
}


</style>
  